//
//  OtherOrder.m
//  cutter
//
//  Created by mac on 16/3/3.
//  Copyright © 2016年 e360. All rights reserved.
//
#import "OtherCart.h"
#import "OtherOrder.h"

@implementation OtherOrderReceiver
-(void)viewDidLoad {
    [super viewDidLoad];
    //
    [self updataComponent:0];
    [self.emailView setText:[AppData objToString:[self.data objectForKey:@"email"] lable:nil]];
    [self.nameView setText:[AppData objToString:[self.data objectForKey:@"truename"] lable:nil]];
    [self.mobileView setText:[AppData objToString:[self.data objectForKey:@"mobile"] lable:nil]];
    [self.addressView setText:[AppData objToString:[self.data objectForKey:@"address"] lable:nil]];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //
    if (self.presentationController) {
        UIView *parent = [[self.navigationController view] superview];
        if (parent) {
            [parent.layer setCornerRadius:6];
        }else{
            parent = [self.view superview];
            if (parent) {
                [parent.layer setCornerRadius:6];
            }
        }
    }
}
//
-(NSMutableDictionary *)data{
    if (_data == nil) {
        [self setData:[NSMutableDictionary dictionary]];
    }
    return _data;
}
-(NSMutableDictionary *)area{
    if (_area == nil) {
        [self setArea:[NSMutableDictionary dictionary]];
    }
    return _area;
}
-(NSMutableArray *)source{
    if (_source == nil) {
        [self setSource:[NSMutableArray array]];
        [self.source addObject:[NSMutableArray array]];
        [self.source addObject:[NSMutableArray array]];
        [self.source addObject:[NSMutableArray array]];
    }
    return _source;
}
//
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return [self.source count];
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    NSArray *item = [self.source objectAtIndex:component];
    return [item count];
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSArray *items = [self.source objectAtIndex:component];
    if (row < items.count) {
        NSDictionary *item = [items objectAtIndex:row];
        return [item objectForKey:@"areaname"];
    }
    return @"";
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSString *key = [NSString stringWithFormat:@"%ld",(long)component];
    [self.area setValue:nil forKey:key];
    if (component < [self.source count]) {
        NSArray *items = [self.source objectAtIndex:component];
        if (row < items.count) {
            NSDictionary *item = [items objectAtIndex:row];
            [self.area setValue:item forKey:key];
        }
    }
    [self updataComponent:component + 1];
    //
    NSArray *keys = [self.area.allKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSInteger a = [obj1 integerValue];
        NSInteger b = [obj1 integerValue];
        if (a < b) {
            return NSOrderedDescending;
        }
        if (a > b) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
    //
    NSMutableArray *temp = [NSMutableArray array];
    for (id key in keys) {
        [temp addObject:[[self.area objectForKey:key] objectForKey:@"areaname"]];
    }
    [self.areaView setText:[temp componentsJoinedByString:@"-"]];
}
-(void)updataComponent:(NSInteger)component{
    if (component < [self.source count]) {
        NSMutableArray *item = [self.source objectAtIndex:component];
        [item removeAllObjects];
        //
        id pid = @"0";
        if (component > 0) {
            NSString *key = [NSString stringWithFormat:@"%ld",(long)component - 1];
            pid = [[self.area objectForKey:key] objectForKey:@"id"];
        }
        if (pid != nil) {
            NSArray *temp = [AppData areaList:pid];
            [item addObjectsFromArray:temp];
        }
        [self.pickerView reloadComponent:component];
        //
        NSInteger row = [self rowAtData:item component:component];
        [self.pickerView selectRow:row inComponent:component animated:NO];
        [self pickerView:self.pickerView didSelectRow:row inComponent:component];
    }
}
-(NSInteger)rowAtData:(NSArray*)data component:(NSInteger)component{
    NSString *aid = nil;
    switch (component) {
        case 2:
            aid = [self.data objectForKey:@"area"];
            break;
        case 1:
            aid = [self.data objectForKey:@"city"];
            break;
        default:
            aid = [self.data objectForKey:@"province"];
            break;
    }
    if (aid) {
        for (uint i=0; i<data.count; i++) {
            id temp = [data objectAtIndex:i];
            if ([[temp objectForKey:@"id"] isEqual:aid]) {
                return i;
            }
        }
    }
    return 0;
}
//
-(IBAction)exitTouch:(id)sender{
    if (self.onSelected) {
        self.onSelected(self, nil);
    }
}
-(IBAction)doneTouch:(id)sender{
    if (self.onSelected) {
        [self.data setValue:nil forKey:@"area"];
        [self.data setValue:nil forKey:@"areaname"];
        [self.data setValue:nil forKey:@"city"];
        [self.data setValue:nil forKey:@"cityname"];
        [self.data setValue:nil forKey:@"province"];
        [self.data setValue:nil forKey:@"provincename"];
        [self.data setValue:self.addressView.text forKey:@"address"];
        [self.data setValue:self.nameView.text forKey:@"truename"];
        [self.data setValue:self.mobileView.text forKey:@"mobile"];
        [self.data setValue:self.emailView.text forKey:@"email"];
        //
        NSArray *keys = [self.area.allKeys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSInteger a = [obj1 integerValue];
            NSInteger b = [obj1 integerValue];
            if (a < b) {
                return NSOrderedDescending;
            }
            if (a > b) {
                return NSOrderedAscending;
            }
            return NSOrderedSame;
        }];
        for (id key in keys) {
            id data = [self.area objectForKey:key];
            switch ([key intValue]) {
                case 2:
                    [self.data setValue:[data objectForKey:@"id"] forKey:@"area"];
                    [self.data setValue:[data objectForKey:@"areaname"] forKey:@"areaname"];
                    break;
                case 1:
                    [self.data setValue:[data objectForKey:@"id"] forKey:@"city"];
                    [self.data setValue:[data objectForKey:@"areaname"] forKey:@"cityname"];
                    break;
                default:
                    [self.data setValue:[data objectForKey:@"id"] forKey:@"province"];
                    [self.data setValue:[data objectForKey:@"areaname"] forKey:@"provincename"];
                    break;
            }
        }
        self.onSelected(self, self.data);
    }
}
@end


//
//
@interface OtherOrderCustomText : UITextField
@end
@implementation OtherOrderCustomText
- (CGRect)textRectForBounds:(CGRect)bounds{
    CGRect rect = [super textRectForBounds:bounds];
    return CGRectInset(rect, 5, 0);
}
- (CGRect)editingRectForBounds:(CGRect)bounds{
    CGRect rect = [super editingRectForBounds:bounds];
    return CGRectInset(rect, 5, 0);
}
@end
//
//
@implementation OtherOrderHead
@end
//
//
@interface OtherOrderCellCellInput : UITextView
@end
@implementation OtherOrderCellCellInput
- (BOOL)becomeFirstResponder{
    if ([self.delegate respondsToSelector:@selector(textViewDidBeginEditing:)]) {
        [self.delegate textViewDidBeginEditing:self];
    }
    return [super becomeFirstResponder];
}
- (BOOL)resignFirstResponder{
    if ([self.delegate respondsToSelector:@selector(textViewDidEndEditing:)]) {
        [self.delegate textViewDidEndEditing:self];
    }
    return [super resignFirstResponder];
}
@end
//
//
@implementation OtherOrderCellCell
- (void)textViewDidBeginEditing:(UITextView *)textView{
    [self.descTips setHidden:YES];
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    if (textView.text.length == 0) {
        [self.descTips setHidden:NO];
        [self.node setValue:@"" forKey:@"remark"];
    }else{
        [self.descTips setHidden:YES];
        [self.node setValue:textView.text forKey:@"remark"];
    }
}
@end
//
//
@implementation OtherOrder
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.commitView addTarget:self action:@selector(commitTouch:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self headerRefresh:nil];
}
-(void)headerRefresh:(TMRefresh*)sender{
    if (self.source == nil) {
        return;
    }
    //
    __weak OtherOrder *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [this.data setValue:this.source forKey:@"cartarr"];
        [this.data setValue:[OtherCart convertData:this.source] forKey:@"data"];
        dispatch_async(dispatch_get_main_queue(), ^{
            id temp = [OtherCart convertData:this.source];
            UITreeNode *root = [this makeNodesWithData:[NSDictionary dictionaryWithObject:temp forKey:@"items"] level:-1];
            [this.tableView setRootNode:root];
            [this updata];
        });
    });
}
-(UITreeNode*)makeNodesWithData:(id)data level:(NSInteger)level{
    static NSInteger identify = 0;
    if ([data isKindOfClass:NSDictionary.class]) {
        UITreeNode *nodes=[[UITreeNode alloc] init];
        nodes.idetify = identify++;
        nodes.level = level;
        nodes.expand = YES;
        nodes.select = NO;
        nodes.value = data;
        //子级列出
        id child = [data objectForKey:@"items"];
        if (child) {
            for (id item in child) {
                [nodes addNode:[self makeNodesWithData:item level:level+1]];
            }
        }
        return nodes;
    }
    return nil;
}
-(NSMutableDictionary *)data{
    if (_data == nil) {
        [self setData:[NSMutableDictionary dictionary]];
    }
    return _data;
}
//
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __weak OtherOrder *this = self;
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *root = segue.destinationViewController;
        if ([[root.viewControllers firstObject] isKindOfClass:OtherOrderReceiver.class]) {
            id receiver = [this.data objectForKey:@"receiver"];
            if (receiver == nil) {
                receiver = [NSMutableDictionary dictionaryWithDictionary:this.client];
            }
            OtherOrderReceiver *ctrl = [root.viewControllers firstObject];
            [ctrl setData:receiver];
            [ctrl setOnSelected:^(id target, id result){
                if (result) {
                    [this.heightLayout setConstant:140];
                    [this.view updateConstraintsIfNeeded];
                    [UIView beginAnimations:nil context:nil];
                    [this.view layoutIfNeeded];
                    [UIView commitAnimations];
                    //
                    [this.data setValue:result forKey:@"receiver"];
                    [this updataReceiver];
                }
                [this dismissViewControllerAnimated:YES completion:nil];
            }];
        }
    }
}
-(void)treeView:(UITreeView *)treeView expandRowAtIndex:(NSInteger)index{
}
-(void)treeView:(UITreeView *)treeView collapseRowAtIndex:(NSInteger)index{
}
-(UITableViewCell *)treeView:(UITreeView *)treeView cellForRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    if (node.level == 0) {
        OtherOrderHead *cell = [treeView dequeueReusableCellWithIdentifier:@"headIdentifier"];
        [cell.nameView setText:[node.value objectForKey:@"name"]];
        return cell;
    }
    if (node.level == 1) {
        OtherOrderHead *cell = [treeView dequeueReusableCellWithIdentifier:@"nameIdentifier"];
        [cell.nameView setText:[node.value objectForKey:@"name"]];
        return cell;
    }
    //
    id detail = [node.value objectForKey:@"product_detail"];
    if ([[node.value objectForKey:@"productid"] intValue] > 0) {
        OtherOrderCellCell *cell = [treeView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
        [cell.priceView setText:[AppData priceToString:[detail objectForKey:@"price"] lable:nil]];
        [cell.countView setText:[AppData countToString:[node.value objectForKey:@"number"] lable:nil]];
        [cell.nameView setText:[AppData objToString:[detail objectForKey:@"productname"] lable:nil]];
        [cell.sizeView setText:[AppData objToString:[detail objectForKey:@"productsn"] lable:nil]];
        [cell.descView setText:[AppData objToString:[node.value objectForKey:@"remark"] lable:nil]];
        [AppData loadImage:[detail objectForKey:@"thumb400_jpg"] view:cell.iconView];
        [cell setNode:node.value];
        return cell;
    }
    OtherOrderCellCell *cell = [treeView dequeueReusableCellWithIdentifier:@"otherIdentifier"];
    [cell.priceView setText:[AppData priceToString:[detail objectForKey:@"price"] lable:nil]];
    [cell.nameView setText:[AppData objToString:[detail objectForKey:@"remark"] lable:nil]];
    return cell;
    
}
-(CGFloat)treeView:(UITreeView *)treeView heightForRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    if (node.level < 2) {
        if ([[node.value objectForKey:@"name"] isEqualToString:@""]) {
            return 0;
        }
        return 40;
    }
    return 119;
}
//
-(void)updataReceiver{
    id receiver = [self.data objectForKey:@"receiver"];
    if (receiver) {
        id address = [receiver objectForKey:@"address"];
        id areaname = [receiver objectForKey:@"areaname"];
        id cityname = [receiver objectForKey:@"cityname"];
        id provincename = [receiver objectForKey:@"provincename"];
        NSMutableArray *temps = [NSMutableArray array];
        if (provincename) {
            [temps addObject:provincename];
        }
        if (cityname) {
            [temps addObject:cityname];
        }
        if (areaname) {
            [temps addObject:areaname];
        }
        if (address) {
            [temps addObject:address];
        }
        //
        NSString *temp = @"<span style='font-family:Helvetica Neue;color:#4A4A4A;line-height:200%%'>"\
        "<span style='font-size:18px;font-weight:bold;'>%@</span><br/>"\
        "<span style='font-size:14px;font-weight:bold;'>%@</span><br/>"\
        "<span style='font-size:14px;'>地址：%@<br/>"\
        "邮箱：%@</span></span>";
        NSString *html = [NSString stringWithFormat:temp,
                          [receiver objectForKey:@"truename"],
                          [receiver objectForKey:@"mobile"],
                          [temps componentsJoinedByString:@" "],
                          [receiver objectForKey:@"email"]];
        [self.receiverView setAttributedText:[self parseHtml:html]];
    }else{
        NSString *html = @"<span style='font-size:18px;color:#4A4A4A;font-weight:bold;'>收货人信息</span>";
        [self.receiverView setAttributedText:[self parseHtml:html]];
    }
}
-(void)updata{
    CGFloat price = 0;
    NSInteger count = 0;
    for (id item in self.source) {
        id temp = [item objectForKey:@"product_detail"];
        if ([temp isKindOfClass:NSDictionary.class]) {
            NSInteger c = [[item objectForKey:@"number"] integerValue];
            CGFloat p = [[temp objectForKey:@"price"] floatValue];
            price += c * p;
            count += c;
        }
    }
    [self.commitView setEnabled:count > 0];
    //
    NSString *htm1 = [NSString stringWithFormat:@"<span style='font-size:14px;color:#4A4A4A'>总共 <span style='color:#4794EF'>%ld</span> 件</span>", (long)count];
    [self.countView setAttributedText:[self parseHtml:htm1]];
    
    NSString *htm2 = [NSString stringWithFormat:@"<span style='font-size:14px;color:#4A4A4A'>商品总计 <span style='color:#4794EF'>￥%0.2f</span></span>", price];
    [self.priceView setAttributedText:[self parseHtml:htm2]];
    //
    [self.data setValue:[self.client objectForKey:@"id"] forKey:@"clientid"];
    [self.data setValue:[NSNumber numberWithInteger:count] forKey:@"number"];
    [self.data setValue:[NSNumber numberWithFloat:price] forKey:@"saleprice"];
    [self.data setValue:nil forKey:@"payment"];
    [self.data setValue:nil forKey:@"money"];
    [self.data setValue:nil forKey:@"desc"];
    //
    if ([self.data objectForKey:@"thedate"] == nil) {
        [self.data setValue:[[NSDate date] toString:@"yyyy-MM-dd"] forKey:@"thedate"];
    }
    if ([self.data objectForKey:@"uuid"] == nil) {
        [self.data setValue:[NSString uuid] forKey:@"uuid"];
    }
}
- (NSAttributedString*)parseHtml:(NSString*)html{
    NSDictionary *options = [NSDictionary dictionaryWithObject:NSHTMLTextDocumentType forKey:NSDocumentTypeDocumentAttribute];
    return [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:nil error:nil];
}
- (IBAction)exitTouch:(id)sender{
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)commitTouch:(id)sender{
    if ([self.data objectForKey:@"receiver"] == nil) {
        [UIAlertController show:nil message:@"收获人信息不能为空!" buttons:nil handler:nil];
        return;
    }
    //
    __weak OtherOrder *this = self;
    [UIAlertController show:nil message:@"是否提交当前订单?" buttons:@[@"提交",@"取消"] handler:^(UIAlertAction *action){
        if ([action.title isEqualToString:@"提交"]) {
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                id data = [AppData userEditSale:this.data client:[this.data objectForKey:@"receiver"]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    if (data) {
                        id root = [this presentingViewController];
                        if ([root respondsToSelector:@selector(setSelectedIndex:)]) {
                            [root setSelectedIndex:5];
                        }
                        [this dismissViewControllerAnimated:YES completion:nil];
                    }else{
                        [UIAlertController show:nil message:@"提交出错,请连接到网络!" buttons:nil handler:nil];
                    }
                });
            });
        }
    }];
}
@end